/*
 * Copyright (C) 2013  Richard Schilling. All rights reserved.
 * contact: coderroadie@gmail.com
 * 
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */

package android.persist.op.sqlite;

import static android.persist.op.sqlite.SQLLogging.SQL_LOG_TAG;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.persist.PersistException;
import android.persist.config.ClassConfig;
import android.persist.config.FieldConfig;
import android.persist.op.OpException;
import android.persist.op.Read;
import android.util.Log;

/**
 * Reads all objects of a given class from the database. Only fields that are
 * directly storable are set. All fields that require additional reads from the
 * database (foreign fields) are set to null.
 * 
 * @author Richard Schilling
 * @param <OT> the class of the object to read.
 * @param <RT> the list type that is returned by {@link #call}.
 * @since 1.0
 */
public class SQLiteRead<OT> extends Read<Class<OT>, List<OT>> {

    /**
     * The database that this operation is applied against.
     * 
     * @since 1.0
     */
    private final SQLiteDatabase mDatabase;

    /**
     * Class configuration object for {@link operand}'s type.
     * 
     * @since 1.0
     */
    private final ClassConfig<OT> mConfig;

    /**
     * {@inheritDoc}
     * <p>
     * Creates a new read operation to read in a class from the database. If
     * {@code criteria} is null then all objects of the specified class type
     * {@code c} are returned by {@link #call()}.
     * 
     * @param db the database to read from.
     * @param c the class type to read.
     * @param criteria an optional parameter that contains field name/value
     *            pairs to use as selection criteria when reading data from the
     *            data store.
     * @since 1.0
     */
    @SuppressWarnings("unchecked")
    public SQLiteRead(SQLiteDatabase db, Class<OT> c, Map<String, Object> criteria) {
        super(c, criteria);

        if (db == null)
            throw new IllegalArgumentException("db cannot be null");

        if (c == null)
            throw new IllegalArgumentException("o cannot be null");

        this.mDatabase = db;
        this.mConfig = (ClassConfig<OT>) ClassConfig.getConfig(c);

    }

    /**
     * Fetches objects from the data store. Foreign reference fields are set as
     * null. To populate those with data utilize {@link SQLiteReadForeign}.
     * 
     * @since 1.0
     * @throws OpException if the database is closed.
     * @throws PersistExcepton the data cannot be read into a new instance of
     *             the class specified in the constructor.
     */
    @Override
    public List<OT> call() {

        if (!mDatabase.isOpen()) {
            throw new OpException("database is closed");
        }

        StringBuilder query = new StringBuilder();
        query.append("SELECT ");
        int sz = mConfig.domesticFields.size();
        int i = 0;
        for (FieldConfig key : mConfig.domesticFields) {
            query.append(key.getPersistedName());
            if (i < sz - 1)
                query.append(", ");
            i++;

        }
        query.append(" FROM '");
        query.append(mConfig.storageName);
        query.append("'");
        if (mCriteria != null) {
            query.append(" WHERE ");
            i = 0;
            sz = mCriteria.size();
            for (Entry<String, Object> e : mCriteria.entrySet()) {
                query.append(e.getKey());
                query.append("=");
                query.append(SQLiteUtil.toStringValue(e.getValue()));
                if (i < sz - 1)
                    query.append(" AND");

                i++;

            }

        }

        if (Log.isLoggable(SQL_LOG_TAG, Log.DEBUG)) {
            Log.d(SQL_LOG_TAG,
                    query.toString());
        }

        List<OT> result = (List<OT>) loadClasses(query.toString());

        return result;

    }

    /**
     * Iterates through a cursor and returns new instances of a class for each
     * item in the cursor. Foreign reference fields are set as null.
     * 
     * @param cursor the cursor to read data from.
     * @return a list of classes deserialized from the cursor fields.
     * @since 1.0
     * @throws PersistExcepton if the value of the field cannot be set.
     */
    private List<OT> loadClasses(String query) {
        Cursor cursor = mDatabase.rawQuery(query.toString(), null);

        try {

            @SuppressWarnings("unchecked")
            List<OT> result = new ArrayList<OT>();

            String[] columns = cursor.getColumnNames();

            if (!cursor.moveToFirst()) {
                return result;
            }

            // convert cursor column values to field values
            try {
                do {

                    OT newObject = operand.newInstance();

                    // iterate through the cursor columns to set non-foreign
                    // values.
                    for (String col : columns) {

                        if (!mConfig.hasField(col)) {
                            continue;
                        }

                        FieldConfig fc = mConfig.getFieldConfig(col);

                        // get the column value - use the proper
                        // cursor.getString/getLong/etc.
                        Object value = SQLiteUtil.getColumnValue(fc, cursor, col);
                        try {
                            fc.field.set(newObject, value);
                        } catch (IllegalArgumentException ex) {
                            Log.i("ERROR", "illegalargumentexception");
                            throw ex;
                        }

                    }
                    result.add(newObject);

                } while (cursor.moveToNext());

            } catch (IllegalAccessException e) {
                throw new PersistException("unable to create instance of " + operand.getName());
            } catch (InstantiationException e) {
                throw new PersistException("unable to create instance of " + operand.getName());
            }

            return result;
        } finally {
            cursor.close();
        }
    }

}
